from epics import PV

from config import get_config
from os import environ
from os.path import isfile

if isfile("./config.py"):
    from config import get_config

others_datas = get_config()["others"]
pv_datas = get_config()["PV"]
environ["EPICS_CA_ADDR_LIST"] = others_datas["EPICS_CA_ADDR_LIST"]
environ["EPICS_CAS_SERVER_PORT"] = others_datas["EPICS_CAS_SERVER_PORT"]

class _PV_Factory:
    _instance = None  # 类变量，用于存储唯一实例  

    def __new__(cls, *args, **kwargs):  
        if cls._instance is None:  # 检查是否已经创建了实例  
            cls._instance = super(_PV_Factory, cls).__new__(cls, *args, **kwargs)  # 创建新实例  
        return cls._instance  # 返回唯一实例  

    def __init__(self):
        if not hasattr(self, 'initialized'):  # 防止多次初始化（仅在第一次创建实例时执行）
            self.initialized = True  # 设置一个标志，表示实例已经初始化
            self.pvs = {}
    def create_pv(self, pv_name):
        if not pv_name in self.pvs.keys():
            self.pvs[pv_name] = PV(pv_name)
        return self.pvs[pv_name]

    def delete_pv(self, pv_name):
        if pv_name in self.pvs.keys():
            del self.pvs[pv_name]
    def __repr__(self):
        return f"PVs:{self.pvs.keys()}"

    def __str__(self):
        return f"PVs:{self.pvs.keys()}"

PV_Factory = _PV_Factory()
